package org.example.netty.test.nio.netty.chat.util;

import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.*;
import org.example.netty.test.nio.netty.chat.common.MessageType;
import org.example.netty.test.nio.netty.chat.protocol.CustomSerialize;

import java.io.*;

/**
 * @author zp
 * @version 1.0
 * @description: JDK序列化工具
 * @date 2023/3/31 19:16
 */
@Slf4j
public class JDKSerializeUtils implements CustomSerialize {
    /**
     * @param obj
     * @return byte[]
     * @description: 序列化方法
     * @author zp
     * @date: 2023/3/31 19:24
     */
    @Override
    public byte[] serialize(Object obj) {
        //省略序列化过程
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(out);
            oos.writeObject(obj);
            return out.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param bytes
     * @description: 反序列化方法
     * @author zp
     * @date: 2023/3/31 19:20
     */
    /**
     * @param byteArray
     * @return
     * @return Object
     * @throws
     * @Description: 重载反序列化对象
     * @author JornTang
     * @date 2017年7月22日
     */
    @Override
    public <T> T deserialize(byte[] byteArray, Class<T> requiredType) {
        Object rv = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (byteArray != null) {
                bis = new ByteArrayInputStream(byteArray);
                is = new ObjectInputStream(bis);
                rv = is.readObject();
            }
        } catch (Exception e) {
            log.error("serialize error ", e);
        } finally {
            close(is);
            close(bis);
        }
        return (T) rv;
    }

    /**
     * @param closeable
     * @description: 关闭流的方法
     * @author zp
     * @date: 2023/3/31 19:32
     */
    private static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                log.error("close stream error", e);
            }
        }
    }
}
